/**
 * @Author: easten
 * @Created: 2024-04-15 23:29:48
 * @Description: 终端管理
 *
 */
import classnames from "classnames";
import React, { useState, useEffect, useMemo } from "react";
import { CpuIcon, RefreshIcon } from "tdesign-icons-react";
import {
  Button,
  Popconfirm,
  Space,
  Table,
  Tag,
  Tree,
  message,
} from "tdesign-react";
import TerminalDrawer from "./TerminalDrawer";
import { ModuleCommonProps, PageParams, TreeDataModel } from "_common/DataType";
import { IotTerminal } from "_common/entity";
import { ApiGateway, ApiTerminal } from "_common/api/iot";
import { TableTitle } from "components";
import Styles from "./index.module.less";

const IotTerminalComp: React.FC<ModuleCommonProps> = (props) => {
  const { axios, className } = props;
  const [pageState, setPageState] = useState<PageParams>({
    pageNum: 1,
    pageSize: 10,
    total: 0,
    list: [],
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([
    1, 2,
  ]);
  const [visible, setVisible] = useState(false);
  const [edit, setEdit] = useState(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [terminalList, setTerminalList] = useState<IotTerminal[]>([]);
  const [gatewayTree, setGatewayTree] = useState<TreeDataModel[]>([]);
  const [selectedGateway, setSelectedGateway] = useState<
    TreeDataModel | undefined
  >();
  const [selectedRow, setSelectedRow] = useState<IotTerminal>();

  const apiGateway = new ApiGateway(axios);
  const apiTerminal = new ApiTerminal(axios);

  useEffect(() => {
    getGatewayList();
  }, []);

  // 获取网关
  const getGatewayList = async () => {
    setLoading(true);
    const response = await apiGateway.getGatewayList();
    if (response && response.code == 200 && response.data) {
      setGatewayTree(
        response.data?.map((item) => {
          return {
            label: item.gatewayName,
            value: item.id,
          };
        })
      );
    }
    setLoading(false);
  };

  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  // 查询
  const getTerminalList = async () => {
    const response = await apiTerminal.getPageList({
      ...pageState,
      gatewayId: selectedGateway?.value,
    });
    if (response && response.code == 200 && response.data) {
      setTerminalList(response.data.list);
      setPageState({
        ...pageState,
        total: response.data.total,
      });
    } else {
      setTerminalList([]);
    }
  };

  const renderLabel = (node: any) => (
    <Tag
      theme="warning"
      variant="outline"
      icon={<CpuIcon color="#EF9735" />}
      size="small"
    >
      网关：{node.data.label}
    </Tag>
  );

  // 删除用户
  const deleteTerminal = async (id: number) => {
    const response = await apiTerminal.deleteTerminal(id);
    if (response && response.code == 200 && response.data) {
      message.success("删除成功");
      getTerminalList();
    }
  };

  useEffect(() => {
    getTerminalList();
  }, [selectedGateway, pageState.pageNum, pageState.pageSize]);

  const treeNode = useMemo(() => {
    return (
      <Tree
        data={gatewayTree}
        activable
        hover
        transition
        label={renderLabel}
        className="ml-0"
        onActive={(e, c) => {
          if (e.length == 0) {
            setSelectedGateway(undefined);
          } else {
            setSelectedGateway(c.node?.data as any);
          }
        }}
      />
    );
  }, [gatewayTree, selectedGateway]);

  return (
    <div className={classnames(className, "flex", "flex-row")}>
      <div className={classnames(Styles.stationTree)}>
        <TableTitle text="网关信息" />
        <div className="pt-4 pr-5 pl-0">{treeNode}</div>
      </div>
      <div className={classnames(Styles.TerminalTable, "pl-5")}>
        <div className="flex flex-row justify-between mb-4">
          <TableTitle text="终端列表" />
          <Space>
            <Button
              onClick={() => {
                setVisible(true);
                setEdit(false);
              }}
            >
              新增终端
            </Button>
            <Button
              icon={<RefreshIcon />}
              variant="outline"
              onClick={() => {
                getTerminalList();
              }}
            ></Button>
          </Space>
        </div>

        <Table
          bordered
          columns={[
            {
              align: "left",
              width: 80,
              ellipsis: true,
              colKey: "index",
              title: "序号",
              cell: ({ rowIndex }) => {
                let _index =
                  (pageState.pageNum - 1) * pageState.pageSize + rowIndex + 1;
                return <span>{_index}</span>;
              },
            },
            {
              align: "left",
              ellipsis: true,
              colKey: "terminalName",
              title: "终端名称",
            },
            {
              align: "left",
              ellipsis: true,
              colKey: "terminalCode",
              title: "终端编号",
            },
            {
              align: "left",
              ellipsis: true,
              colKey: "address",
              title: "485总线地址",
            },
            {
              align: "center",
              fixed: "right",
              width: 220,
              colKey: "op",
              title: "操作",
              cell({ row }) {
                return (
                  <>
                    <Button
                      theme="success"
                      variant="text"
                      onClick={() => {
                        setVisible(true);
                        setEdit(true);
                        setSelectedRow(row);
                      }}
                    >
                      编辑
                    </Button>
                    <Popconfirm
                      content="确认删除吗"
                      destroyOnClose
                      placement="top"
                      showArrow
                      theme="default"
                      onConfirm={() => deleteTerminal(row.id)}
                    >
                      <Button theme="primary" variant="text">
                        删除
                      </Button>
                    </Popconfirm>
                  </>
                );
              },
            },
          ]}
          loading={loading}
          data={terminalList}
          rowKey="index"
          selectedRowKeys={selectedRowKeys}
          verticalAlign="middle"
          hover
          onSelectChange={onSelectChange}
          pagination={{
            pageSize: pageState.pageSize,
            total: pageState.total,
            current: pageState.pageNum,
            showJumper: true,
            onCurrentChange(current) {
              setPageState({
                ...pageState,
                pageNum: current,
              });
            },
            onPageSizeChange(size) {
              setPageState({
                ...pageState,
                pageSize: size,
              });
            },
          }}
        />
      </div>

      <TerminalDrawer
        onSuccess={() => {
          setVisible(false);
          getTerminalList();
        }}
        axios={axios}
        open={visible}
        edit={edit}
        gateway={selectedGateway}
        value={selectedRow}
      />
    </div>
  );
};
export default IotTerminalComp;
